import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/features/finance/models/monthly_bill_model.dart';
import 'package:family_app/src/features/finance/models/yearly_stats_model.dart';
import 'package:family_app/src/features/finance/models/bill_detail_model.dart';
import 'package:family_app/src/common/services/network_service.dart';

/// 财务服务提供者
final financeServiceProvider = Provider<FinanceService>((ref) {
  final networkService = ref.watch(networkServiceProvider);
  return FinanceService(networkService);
});

/// 财务服务
/// 负责财务相关的业务逻辑，所有数据通过网络接口获取，不使用本地缓存
class FinanceService {
  final NetworkService _networkService;
  
  // 模拟用户ID，实际应用中应该从用户认证服务获取
  static const int _defaultUserId = 1;

  FinanceService(this._networkService);

  /// 获取所有交易记录
  Future<List<TransactionModel>> getTransactions() async {
    try {
      final response = await _networkService.getTransactionList(
        userId: _defaultUserId,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          final responseData = data['data'] as Map<String, dynamic>;
          final billData = responseData['billData'] as List;
          return billData
              .map((json) => TransactionModel.fromJson(json))
              .toList();
        }
      }
      
      // 如果API失败，返回模拟数据
      return _generateMockTransactions();
    } catch (e) {
      print('获取交易记录失败: $e');
      // 网络错误时返回模拟数据
      return _generateMockTransactions();
    }
  }

  /// 获取指定日期范围内的交易记录
  Future<List<TransactionModel>> getTransactionsByDateRange(
      DateTime startDate, DateTime endDate) async {
    try {
      // 格式化日期为 yyyy-MM-dd 格式
      final dateStr = '${startDate.year.toString().padLeft(4, '0')}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')}';
      
      print('=== API调用开始 ===');
      print('调用getBillDetailList API');
      print('参数: userId=$_defaultUserId, type=0, secondClassifyId=-1, date=$dateStr');
      print('开始时间: $startDate, 结束时间: $endDate');
      
      final response = await _networkService.getBillDetailList(
        userId: _defaultUserId,
        type: 0, // 支出类型
        secondClassifyId: -1, // 固定为-1
        date: dateStr,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          final responseData = data['data'] as Map<String, dynamic>;
          final billData = responseData['billData'] as List;
          final List<TransactionModel> transactions = [];
          for (final dayData in billData) {
            final itemList = dayData['itemList'] as List<dynamic>?;
            if (itemList != null) {
              for (final item in itemList) {
                // 使用BillItem解析API响应，然后转换为TransactionModel
                final billItem = BillItem.fromJson(item);
                transactions.add(_convertBillItemToTransaction(billItem));
              }
            }
          }
          return transactions;
        }
      }
      
      // 如果API失败，从模拟数据中筛选
      final allTransactions = _generateMockTransactions();
      return allTransactions.where((transaction) {
        return transaction.transactionDate
                .isAfter(startDate.subtract(const Duration(days: 1))) &&
            transaction.transactionDate
                .isBefore(endDate.add(const Duration(days: 1)));
      }).toList();
    } catch (e) {
      print('获取指定日期范围交易记录失败: $e');
      // 网络错误时从模拟数据中筛选
      final allTransactions = _generateMockTransactions();
      return allTransactions.where((transaction) {
        return transaction.transactionDate
                .isAfter(startDate.subtract(const Duration(days: 1))) &&
            transaction.transactionDate
                .isBefore(endDate.add(const Duration(days: 1)));
      }).toList();
    }
  }

  /// 获取指定月份的交易记录
  Future<List<TransactionModel>> getTransactionsByMonth(
      int year, int month) async {
    try {
      final startDate = DateTime(year, month, 1);
      final endDate = DateTime(year, month + 1, 0); // 月份的最后一天
      return getTransactionsByDateRange(startDate, endDate);
    } catch (e) {
      print('获取指定月份交易记录失败: $e');
      return [];
    }
  }

  /// 添加交易记录
  Future<TransactionModel?> addTransaction({
    required int amount,
    required TransactionType type,
    required String category,
    String? description,
    DateTime? transactionDate,
  }) async {
    try {
      // 将分类映射为分类ID
      final classifyId = _getCategoryClassifyId(type, category);
      final secondClassifyId = _getCategorySecondClassifyId(category);
      
      // 格式化时间
      final dateTime = transactionDate ?? DateTime.now();
      final timeString = _formatDateTime(dateTime);
      
      // 转换交易类型为数字
      final typeValue = type == TransactionType.expense ? 0 : 1;
      
      final response = await _networkService.createTransaction(
        userId: _defaultUserId.toString(),
        money: amount.toString(), // 直接使用金额
        classifyId: classifyId,
        secondClassifyId: secondClassifyId,
        createTime: timeString,
        updateTime: timeString,
        type: typeValue,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200) {
          // API保存成功，创建本地记录
          return TransactionModel.create(
            amount: amount,
            type: type,
            category: category,
            description: description,
            transactionDate: transactionDate,
          );
        }
      }
      
      // 如果API失败，创建本地模拟记录（仅用于演示）
      return TransactionModel.create(
        amount: amount,
        type: type,
        category: category,
        description: description,
        transactionDate: transactionDate,
      );
    } catch (e) {
      print('添加交易记录失败: $e');
      return null;
    }
  }

  /// 获取分类的主分类ID
  String _getCategoryClassifyId(TransactionType type, String category) {
    // 根据交易类型返回主分类ID
    if (type == TransactionType.income) {
      return '1'; // 收入主分类
    } else {
      return '2'; // 支出主分类
    }
  }

  /// 获取分类的二级分类ID
  String _getCategorySecondClassifyId(String category) {
    // 创建分类到ID的映射
    final categoryMap = {
      // 收入分类
      '工资': '1',
      '奖金': '2',
      '投资收益': '3',
      '兼职收入': '4',
      '礼金': '5',
      '退款': '6',
      '其他收入': '7',
      
      // 支出分类
      '餐饮': '8',
      '购物': '9',
      '交通': '10',
      '住房': '11',
      '娱乐': '12',
      '医疗': '13',
      '教育': '14',
      '旅行': '15',
      '日用品': '16',
      '数码': '17',
      '服饰': '18',
      '美容': '19',
      '社交': '20',
      '礼物': '21',
      '其他支出': '22',
    };
    
    return categoryMap[category] ?? '1'; // 默认返回1
  }

  /// 格式化时间为 "yyyy-MM-dd HH:mm:ss" 格式
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year.toString().padLeft(4, '0')}-'
        '${dateTime.month.toString().padLeft(2, '0')}-'
        '${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:'
        '${dateTime.minute.toString().padLeft(2, '0')}:'
        '${dateTime.second.toString().padLeft(2, '0')}';
  }

  /// 更新交易记录
  Future<TransactionModel?> updateTransaction({
    required String id,
    int? amount,
    TransactionType? type,
    String? category,
    String? description,
    DateTime? transactionDate,
  }) async {
    try {
      final response = await _networkService.updateTransaction(
        transactionId: id,
        amount: amount,
        type: type?.name,
        category: category,
        description: description,
        transactionDate: transactionDate,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          return TransactionModel.fromJson(data['data']);
        }
      }
      
      return null;
    } catch (e) {
      print('更新交易记录失败: $e');
      return null;
    }
  }

  /// 删除交易记录
  Future<bool> deleteTransaction(String id) async {
    try {
      final response = await _networkService.deleteTransaction(
        transactionId: id,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        return data['code'] == 200;
      }
      
      return false;
    } catch (e) {
      print('删除交易记录失败: $e');
      return false;
    }
  }

  /// 获取收入统计
  Future<int> getTotalIncome({DateTime? startDate, DateTime? endDate}) async {
    try {
      final response = await _networkService.getIncomeExpenseStats(
        userId: _defaultUserId,
        startDate: startDate,
        endDate: endDate,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          return data['data']['totalIncome'] ?? 0;
        }
      }
      
      // 如果API失败，从模拟数据计算
      List<TransactionModel> transactions;
      if (startDate != null && endDate != null) {
        transactions = await getTransactionsByDateRange(startDate, endDate);
      } else {
        transactions = await getTransactions();
      }

      final incomeTransactions = transactions
          .where((transaction) => transaction.type == TransactionType.income)
          .toList();

      int total = 0;
      for (var transaction in incomeTransactions) {
        total += transaction.amount;
      }

      return total;
    } catch (e) {
      print('获取收入统计失败: $e');
      return 0;
    }
  }

  /// 获取支出统计
  Future<int> getTotalExpense({DateTime? startDate, DateTime? endDate}) async {
    try {
      final response = await _networkService.getIncomeExpenseStats(
        userId: _defaultUserId,
        startDate: startDate,
        endDate: endDate,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          return data['data']['totalExpense'] ?? 0;
        }
      }
      
      // 如果API失败，从模拟数据计算
      List<TransactionModel> transactions;
      if (startDate != null && endDate != null) {
        transactions = await getTransactionsByDateRange(startDate, endDate);
      } else {
        transactions = await getTransactions();
      }

      final expenseTransactions = transactions
          .where((transaction) => transaction.type == TransactionType.expense)
          .toList();

      int total = 0;
      for (var transaction in expenseTransactions) {
        total += transaction.amount;
      }

      return total;
    } catch (e) {
      print('获取支出统计失败: $e');
      return 0;
    }
  }

  /// 获取余额
  Future<int> getBalance({DateTime? startDate, DateTime? endDate}) async {
    try {
      final totalIncome =
          await getTotalIncome(startDate: startDate, endDate: endDate);
      final totalExpense =
          await getTotalExpense(startDate: startDate, endDate: endDate);
      return totalIncome - totalExpense;
    } catch (e) {
      print('获取余额失败: $e');
      return 0;
    }
  }

  /// 获取分类统计
  Future<Map<String, int>> getCategoryStats({
    required TransactionType type,
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    try {
      final response = await _networkService.getCategoryStats(
        userId: _defaultUserId,
        type: type.name,
        startDate: startDate,
        endDate: endDate,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          final Map<String, dynamic> rawStats = data['data'];
          return rawStats.map((key, value) => MapEntry(key, value as int));
        }
      }
      
      // 如果API失败，从模拟数据计算
      List<TransactionModel> transactions;
      if (startDate != null && endDate != null) {
        transactions = await getTransactionsByDateRange(startDate, endDate);
      } else {
        transactions = await getTransactions();
      }

      // 筛选指定类型的交易
      final filteredTransactions =
          transactions.where((t) => t.type == type).toList();

      // 按分类统计金额
      final Map<String, int> stats = {};
      for (final transaction in filteredTransactions) {
        final category = transaction.category;
        stats[category] = (stats[category] ?? 0) + transaction.amount;
      }

      return stats;
    } catch (e) {
      print('获取分类统计失败: $e');
      return {};
    }
  }

  /// 获取所有分类
  Future<List<String>> getAllCategories() async {
    try {
      final response = await _networkService.getAllCategories(
        userId: _defaultUserId,
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data;
        if (data['code'] == 200 && data['data'] != null) {
          return List<String>.from(data['data']);
        }
      }
      
      // 如果API失败，从模拟数据提取分类
      final transactions = await getTransactions();
      
      // 提取所有不重复的分类
      final Set<String> categories = {};
      for (final transaction in transactions) {
        categories.add(transaction.category);
      }
      
      // 转换为列表并排序
      final sortedCategories = categories.toList()..sort();
      return sortedCategories;
    } catch (e) {
      print('获取所有分类失败: $e');
      return [];
    }
  }

  /// 获取月度账单列表
  /// 从接口获取指定年份和用户ID的月度账单数据
  Future<List<MonthlyBillModel>> getMonthlyBillList({
    required int year,
    required int userId,
  }) async {
    try {
      final response = await _networkService.getMonthlyBillList(
        year: year,
        userId: userId,
      );

      print('API响应状态码: ${response.statusCode}');
      print('API响应数据: ${response.data}');

      // 检查响应是否为空或格式不正确
      if (response.data == null) {
        print('API响应数据为空');
        return _generateMockMonthlyBills(year);
      }

      // 解析响应数据
      final monthlyBillResponse = MonthlyBillResponse.fromJson(response.data);

      // 检查响应状态
      if (monthlyBillResponse.code == 200) {
        // 按月份排序（升序）
        final sortedBills = List<MonthlyBillModel>.from(monthlyBillResponse.data)
          ..sort((a, b) => int.parse(a.month).compareTo(int.parse(b.month)));
        return sortedBills;
      } else {
        throw Exception('获取月度账单失败: ${monthlyBillResponse.message}');
      }
    } catch (e) {
      // 发生错误时返回模拟数据
      print('获取月度账单列表出错: $e');
      return _generateMockMonthlyBills(year);
    }
  }

  /// 获取年度统计数据
  /// 从接口获取指定年份和用户ID的年度收入支出统计
  Future<YearlyStatsModel?> getYearlyStats({
    required int year,
    required int userId,
  }) async {
    try {
      final response = await _networkService.getYearlyStats(
        year: year,
        userId: userId,
      );

      print('年度统计API响应状态码: ${response.statusCode}');
      print('年度统计API响应数据: ${response.data}');

      // 检查响应是否为空或格式不正确
      if (response.data == null) {
        print('年度统计API响应数据为空');
        return null;
      }

      // 解析响应数据
      final yearlyStatsResponse = YearlyStatsResponse.fromJson(response.data);

      // 检查响应状态
      if (yearlyStatsResponse.code == 200) {
        return yearlyStatsResponse.data;
      } else {
        throw Exception('获取年度统计失败: ${yearlyStatsResponse.message}');
      }
    } catch (e) {
      print('获取年度统计数据出错: $e');
      return null;
    }
  }

  /// 获取详细账单列表
  Future<BillDetailData?> getBillDetailList({
    required int userId,
    required int type,
    required int secondClassifyId,
    required String date,
  }) async {
    try {
      print('正在获取详细账单列表: userId=$userId, type=$type, secondClassifyId=$secondClassifyId, date=$date');
      
      final response = await _networkService.getBillDetailList(
        userId: userId,
        type: type,
        secondClassifyId: secondClassifyId,
        date: date,
      );

      print('详细账单列表API响应状态码: ${response.statusCode}');
      print('详细账单列表API响应数据: ${response.data}');

      if (response.data == null) {
        print('详细账单列表API响应数据为空');
        return null;
      }

      // 解析响应数据
      final billDetailResponse = BillDetailResponse.fromJson(response.data);

      // 检查响应状态
      if (billDetailResponse.code == 200) {
        return billDetailResponse.data;
      } else {
        throw Exception('获取详细账单列表失败: ${billDetailResponse.message}');
      }
    } catch (e) {
      print('获取详细账单列表出错: $e');
      return null;
    }
  }

  /// 生成模拟交易数据
  List<TransactionModel> _generateMockTransactions() {
    final now = DateTime.now();
    final transactions = <TransactionModel>[];

    // 收入
    transactions.add(TransactionModel.create(
      amount: 500000, // 5000元
      type: TransactionType.income,
      category: '工资',
      description: '3月工资',
      transactionDate: DateTime(now.year, now.month, 10),
    ));

    transactions.add(TransactionModel.create(
      amount: 100000, // 1000元
      type: TransactionType.income,
      category: '兼职收入',
      description: '周末兼职',
      transactionDate: DateTime(now.year, now.month, 20),
    ));

    // 支出
    transactions.add(TransactionModel.create(
      amount: 150000, // 1500元
      type: TransactionType.expense,
      category: '住房',
      description: '房租',
      transactionDate: DateTime(now.year, now.month, 5),
    ));

    transactions.add(TransactionModel.create(
      amount: 20000, // 200元
      type: TransactionType.expense,
      category: '餐饮',
      description: '超市购物',
      transactionDate: DateTime(now.year, now.month, 12),
    ));

    transactions.add(TransactionModel.create(
      amount: 30000, // 300元
      type: TransactionType.expense,
      category: '交通',
      description: '加油',
      transactionDate: DateTime(now.year, now.month, 15),
    ));

    transactions.add(TransactionModel.create(
      amount: 50000, // 500元
      type: TransactionType.expense,
      category: '娱乐',
      description: '电影和晚餐',
      transactionDate: DateTime(now.year, now.month, 18),
    ));

    return transactions;
  }

  /// 生成模拟月度账单数据
  List<MonthlyBillModel> _generateMockMonthlyBills(int year) {
    // 模拟数据，与用户提供的API返回格式一致
    return [
      MonthlyBillModel(
        yearMonth: '$year-01',
        totalExpenseMoney: 2256,
        totalIncomeMoney: 0,
        dayMonth: null,
      ),
      MonthlyBillModel(
        yearMonth: '$year-08',
        totalExpenseMoney: 22,
        totalIncomeMoney: 0,
        dayMonth: null,
      ),
      MonthlyBillModel(
        yearMonth: '$year-02',
        totalExpenseMoney: 12,
        totalIncomeMoney: 0,
        dayMonth: null,
      ),
    ];
  }

  /// 将BillItem转换为TransactionModel
  TransactionModel _convertBillItemToTransaction(BillItem billItem) {
    // 转换交易类型
    final transactionType = billItem.type == 0 
        ? TransactionType.expense 
        : TransactionType.income;
    
    // 解析日期
    DateTime transactionDate;
    try {
      transactionDate = DateTime.parse(billItem.createTime);
    } catch (e) {
      // 如果解析失败，使用当前时间
      transactionDate = DateTime.now();
    }
    
    // 转换金额（API返回的money字段已经是正确的金额，直接转换为分）
    final amountInCents = (billItem.money * 100).round();
    
    return TransactionModel(
      id: billItem.id.toString(),
      amount: amountInCents,
      type: transactionType,
      category: billItem.name ?? '未分类', // 处理name为null的情况
      description: billItem.remark?.isEmpty == true ? null : billItem.remark, // 安全处理remark为null的情况
      transactionDate: transactionDate,
      createdAt: transactionDate,
      updatedAt: transactionDate,
    );
  }
}
